package fw.qaz.asmx.reader.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import fw.qaz.asmx.reader.FloatingWindowService;
import fw.qaz.asmx.reader.R;
import fw.qaz.asmx.reader.SettingCenter;
import fw.qaz.asmx.reader.parser.TxtParser;
import fw.qaz.asmx.reader.utils.BookShelfUtil;
import fw.qaz.asmx.reader.view.ReadView;

public class ReadFragment extends Fragment implements
        GestureDetector.OnGestureListener
{
    private ReadView rv;
    private TxtParser txtParser;
    private File book;
    private int progress;

    private GestureDetectorCompat gesturer;

    public ReadFragment()
    {
    }

    @Override public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle b = getArguments();
        book = new File(b.getString("FilePath", ""));
        progress = b.getInt("Progress", 0);
    }

    @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.fragment_read,container,false);
        rv = (ReadView) v;

        txtParser = new TxtParser(rv, SettingCenter.getFontSize(getActivity()),
                                  SettingCenter.getFontColor(getActivity()),
                                  SettingCenter.getBackgroundColor(getActivity()));
        //
        txtParser.openBook(book.getAbsolutePath());
        txtParser.setBeginPos(progress);
        //
        txtParser.prevPage();
        txtParser.freshUI();

        rv.postInvalidate();
        //
        gesturer = new GestureDetectorCompat(getActivity(), this);
        //
        rv.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent e)
            {
                return gesturer.onTouchEvent(e);
            }
        });
        return v;
    }

    @Override public boolean onSingleTapUp(MotionEvent e)
    {
        if (e.getX() < rv.getWidth() / 3)
        {
            txtParser.prevPage();
            if (txtParser.isfirstPage())
            {
                Toast.makeText(getActivity(), R.string.first_page, Toast.LENGTH_SHORT)
                     .show();
                return true;
            }
            txtParser.freshUI();
        }
        else if (e.getX() > rv.getWidth() / 3 * 2)
        {
            txtParser.nextPage();
            if (txtParser.islastPage())
            {
                Toast.makeText(getActivity(), R.string.end_page, Toast.LENGTH_SHORT)
                     .show();
                return true;
            }
            txtParser.freshUI();
        }
        else
        {
            //在这里弹出菜单（用户点击阅读界面的屏幕中间位置时）
        }
        rv.postInvalidate();
        return false;
    }

    @Override public void onLongPress(MotionEvent e)
    {
        TextView tv = new TextView(getActivity());
        tv.setText(rv.getText());
        tv.setTextColor(Color.BLACK);
        tv.setTextIsSelectable(true);
        new AlertDialog.Builder(getActivity())
                .setTitle("Please select and copy!")
                .setView(tv)
                .show();

        //保存书签
        BookShelfUtil.saveBookMaxProgress(new File(book.getAbsolutePath()),
                                          txtParser.getCurPostionBeg());
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        return false;
    }

    @Override public void onPause()
    {
        super.onPause();
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        return false;
    }

    @Override public boolean onDown(MotionEvent e)
    {
        return true;
    }

    @Override public void onShowPress(MotionEvent e)
    {
    }

    public void createFloatView()
    {
        Intent i = new Intent(getActivity(), FloatingWindowService.class);
        i.putExtra("Path", book.getAbsolutePath());
        i.putExtra("Progress", txtParser.getCurPostion());
        getActivity().startService(i);
        Toast.makeText(getActivity(), "CREATE:" + getActivity().startService(i) + "/",
                       Toast.LENGTH_SHORT).show();
    }
}
